package edu.washington.vaccine.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import edu.washington.vaccine.R;
import edu.washington.vaccine.backend.Patient;
import edu.washington.vaccine.backend.VaccineDB;
import edu.washington.vaccine.backend.VaccineLocalHelper;

/*
 * Displays results from the Search Patient Activity form
 * Listings are shown based on the Patients toString
 */



public class SearchResultsActivity  extends ListActivity {
	@SuppressWarnings("unused")
	private static final String TAG = "SearchResultsActivity";
	VaccineDB db = VaccineDB.getInstance();
	VaccineLocalHelper localdb = VaccineLocalHelper.getInstance(this);
	Patient p;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Bundle data = getIntent().getExtras();
		p = (Patient) data.getSerializable("patient");
		
		Iterator<Patient> i;
		if (db.isOnlineMode()) {
			i = db.searchPatientsFromDB(p);
		} else {
			i = localdb.searchPatientsFromDB(p);
		}

		if (i == null) {
			if (db.isOnlineMode()) {
				i = db.getPatientsFromDB();				
			} else {
				i = localdb.getPatientsFromDB();
			}
		}
		
		final List<Patient> pArray = new ArrayList<Patient>();

		while (i.hasNext()) {
			pArray.add(i.next());		  
		}
//		Log.d("array", ""+ pArray.size());
		setListAdapter(new ArrayAdapter<Patient>(this, R.layout.list_item, pArray));

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);
        lv.setFocusable(true);
        lv.requestFocus();
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				Patient pat = pArray.get(position);
				Intent i = new Intent(SearchResultsActivity.this, PatientDataActivity.class);
				i.putExtra("patient", pat);
				i.putExtra("oldPatient", p);
//				VaccineActivity parentActivity = (VaccineActivity)getParent();
//				parentActivity.replaceContentView("nextactivity", i);
				FirstGroup.group.addChildActivity("nextactivity", i);
			}
		});
		
	}
	
	@Override
	public void onBackPressed() {
//		Intent i = new Intent(this, SearchPatientActivity.class);
//		VaccineActivity parentActivity = (VaccineActivity)getParent();
//		parentActivity.replaceContentView("search", i);
		FirstGroup.group.back();
	}
}